const apiURL = 'http://localhost:4000';

const wxRequest = (params) => {
    return new Promise((resolve, reject) => {
        let header = {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        };
        let token = wx.getStorageSync('token')
        if (token) {
            header['Authorization'] = `Bearer ${token}`
        }
        if (params.header) {
            header = Object.assign(header, params.header)
        }
        wx.request({
            url: `${apiURL}${params.url}`,
            method: params.method || 'GET',
            data: params.data || {},
            header,
            success: (res) => {
                if (res.statusCode != 200) {
                    wx.showToast({
                        title: res.data.error,
                        icon:'none'
                    })
                } else {
                    resolve(res.data)
                }
            },
            fail: (err) => {
                reject(err)
            }
        });
    })

};

const createUser = async (params) => {
    return wxRequest({
        url: `/users`,
        method: 'POST',
        data: params.data
    });
};

const loginUser = async (params) => {
    return wxRequest({
        url: `/users/auth`,
        method: 'POST',
        data: params.data
    });
};
const getUser = async (params) => {
    return wxRequest({
        url: `/users/${params.data}`
    });
};

module.exports = {
    createUser,
    loginUser,
    getUser
};